﻿using System;
using System.Reflection;
using AOPDemo.Domain;
using AOPDemo.Interfaces;
using AOPDemo.Services;
using PostSharp.Aspects;

namespace AOPDemo.Aspects
{
    [Serializable]
    public class LogExecutionTime : OnMethodBoundaryAspect
    {
        [NonSerialized] private ILoggingService loggingService;

        public override void RuntimeInitialize(MethodBase method)
        {
            loggingService = new ConsoleLoggingService();
        }

        public override void OnEntry(MethodExecutionArgs args)
        {
            loggingService.LogMessage(LogLevel.Info, "Starting to execute " + args.Method.Name);
            args.MethodExecutionTag = DateTime.UtcNow;
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            var startTime = (DateTime) args.MethodExecutionTag;
            TimeSpan executionTime = DateTime.UtcNow.Subtract(startTime);
            loggingService.LogMessage(LogLevel.Info,
                                      string.Format("Finished executing {0}, this took {1} seconds.", args.Method.Name,
                                                    executionTime.TotalSeconds));
        }
    }
}